<?php
// +----------------------------
// | Created by PhpStorm
// +----------------------------
// | Author: YnnSon
// +----------------------------
namespace app\api\controller\v1;

use app\api\model\Coupon as CouponModel;
use app\api\model\CouponLog as CouponLogModel;
use app\api\validate\ParameterMustBePositiveInteger;
use app\lib\exception\SuccessMessage;
use app\lib\exception\BaseException;
use think\Request;
use app\api\service\Token;

/**
 * 优惠券
 * Class Coupon
 * @package app\api\controller\v1
 */
class Coupon extends BaseController
{
    /**
     * @desc 检查用户权限
     */
    protected $beforeActionList = [
        'checkUserScope' => ['only' => 'getcouponlist,getcouponlist'], // 方法名必须全部小写，逗号中间不能有空格！！！
    ];

    /**
     * @Desc 根据type查询已领取或未领取的优惠券
     * @param $type
     * @param $page
     * @return array
     */
    public function getCouponList($type,$page)
    {
        return CouponModel::getCouponList($type,$page);
    }

    /**
     * @Desc 添加优惠券领取记录
     *
     * @return array
     */
    public function insertCouponLog()
    {
        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
        $param = Request::instance()->post();

        $coupon_one = CouponModel::getCouponOne($param['id']);
        if($coupon_one['status'] == 2){
            return new BaseException(['code'=>902, 'message'=>'优惠券已失效']);
        }
        if($coupon_one['take_count'] >= $coupon_one['number']){
            return new BaseException(['code'=>902, 'message'=>'优惠券已被领空']);
        }
        if(time() > $coupon_one['end_time']['val']){
            return new BaseException(['code'=>902, 'message'=>'优惠券已过期']);
        }

        $id = Token::getUidFromCache();
        $add_data = ['coupon_id'=>$param['id'], 'user_weixin_id'=>$id, 'create_time'=>time(), 'use_status'=>1, 'get_type'=>1, 'use_start_time'=>$coupon_one['valid_start_time'], 'use_end_time'=>$coupon_one['valid_end_time']];

        $res = CouponLogModel::insertCouponLog($add_data);
        if($res){
            return new SuccessMessage();
        }else{
            return new BaseException(['code'=>904, 'message'=>'领取失败']);
        }
    }
//
//
//    public function updateMessageDetail($id)
//    {
//        (new ParameterMustBePositiveInteger())->scene('id')->goCheck();
//        MessageModel::updateMessageDetail($id);
//        return new SuccessMessage();
//    }

}